﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace HtmlExtractor.Config
{
    public class ExtractorConfig
    {
        public ExtractorConfig()
        { }
        public ExtractorConfig(string configUri)
        {
            ConfigUri = configUri;
        }
        private string GetDomain(string absolutUri)
        {
            string pattern = @"\b(?:https?|ftp)://(?<domain>[-A-Z0-9.]+)";
            string domain;
            SegmentRegex.TryRequiredSingleGroupMatch(absolutUri,pattern,RegexOptions.IgnoreCase,out domain);
            return domain;
        }
        public string ConfigUri;
        public bool TryGetDomainConfig(string parseUri,out string domaiUri)
        {
            string domain = GetDomain(parseUri);
            XElement config = XElement.Load(ConfigUri,LoadOptions.PreserveWhitespace);
            var uri = (from d in config.Elements()
                      where (string)d.Attribute("domain") == domain
                      select (string)d.Element("Uri")).SingleOrDefault();
            if (uri != null)
            {
                domaiUri = uri;
                return true;
            }
            else
            {
                domaiUri = null;
                return false;
            }
        }
    }
}
